package com.zmc.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zmc.common.constant.ResponseConstants;
import com.zmc.common.exception.base.ThirdBaseException;

import java.util.List;

/**
 * @Author：zmc
 * @Date：2024/11/26 10:04
 */
public class JsonUtils {

    public static<T> T transToClass(R r,Class<T> t) {
        int code = Integer.parseInt(r.get(ResponseConstants.CODE_KEY).toString());
        if (ResponseConstants.CODE_VALUE != code) {
            throw new ThirdBaseException(r.get(ResponseConstants.MSG_KEY).toString());
        }
        return JSONObject.parseObject(JSON.toJSONString(r.get(ResponseConstants.DATA_KEY)),t);
    }

    public static<T> List<T> transToArrayClass(R r, Class<T> t) {
        int code = Integer.parseInt(r.get(ResponseConstants.CODE_KEY).toString());
        if (ResponseConstants.CODE_VALUE != code) {
            throw new ThirdBaseException(r.get(ResponseConstants.MSG_KEY).toString());
        }
        return JSONArray.parseArray(JSON.toJSONString(r.get(ResponseConstants.DATA_KEY)), t);
    }

    public static<T> PageUtils transToArrayClassPage(R r, Class<T> t) {
        int code = Integer.parseInt(r.get(ResponseConstants.CODE_KEY).toString());
        if (ResponseConstants.CODE_VALUE != code) {
            throw new ThirdBaseException(r.get(ResponseConstants.MSG_KEY).toString());
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(r.get(ResponseConstants.DATA_KEY)));
        List<T> list = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("list")), t);
        long total = Long.parseLong(JSON.toJSONString(jsonObject.get("total")));
        long pageSize = Long.parseLong(JSON.toJSONString(jsonObject.get("pageSize")));
        long pageNum = Long.parseLong(JSON.toJSONString(jsonObject.get("pageNum")));
        return new PageUtils(list, total,pageSize, pageNum);
    }

    public static void isOk(R r) {
        int code = Integer.parseInt(r.get(ResponseConstants.CODE_KEY).toString());
        if (ResponseConstants.CODE_VALUE != code) {
            throw new ThirdBaseException(r.get(ResponseConstants.MSG_KEY).toString());
        }
    }
}
